package _01_动态数组;

import java.util.*;

public class _56_合并区间 {

    public static void main(String[] args) {

        _56_合并区间 v = new _56_合并区间();

        int[][] ins = new int[][]{
                {5, 5},
                {1, 3},
                {3, 5},
                {4, 6},
                {1, 1},
                {3, 3},
                {5, 6},
                {3, 3},
                {2, 4},
                {0, 0},
        };
        int[][] merge = v.merge(ins);

        for (int[] ints : merge) {
            System.out.println(Arrays.toString(ints));
        }
    }

    public int[][] merge(int[][] intervals) {
        // 进行数组的排序操作
        Arrays.sort(intervals, Comparator.comparingInt((int[] a) -> a[0]));
        List<int[]> results = new ArrayList<>();
        int left = 0;
        int end = intervals.length;
        while (left < end) {
            int right = left;
            int startEle = intervals[left][1];
            while (true) {
                int next = right + 1;
                if (next < end && startEle >= intervals[next][0]) {
                    startEle = Math.max(startEle, intervals[++right][1]);
                } else {
                    // 保存数据
                    results.add(new int[]{intervals[left][0], startEle});
                    left = right + 1;
                    break;
                }
            }
        }
        // toArray返回什么，参数写什么
        return results.toArray(new int[results.size()][2]);
    }

}
